<?php


header("Content-Type: text/html; charset=utf-8");
require_once("conn.inc");
date_default_timezone_set("PRC");



$mysql = new Mysql();

$bg_id = $_POST['bg_id'];
$tea_id = $_POST['tea_id'];
$username = $_POST['username'];

$sql = sprintf ("SELECT * FROM %s WHERE name = \"%s\"","people",$username);


$people = $mysql->select($sql);

$ret = array();
if ((!$people) or count ($people) == 0) {
	$ret["statu"] = "error";
	$ret["error_info"] = "不能查到报告人信息".$sql;
	echo json_encode($ret);
	return;
}

$people_id = $people[0]["id"];

$query = sprintf ('select * from selection where bg_id = %d and people_id = %d',$bg_id,$people_id);

$query_result = $mysql->select($query);
if ((!$query_result) || count($query_result) == 0) {
	$strsql = sprintf ('Insert into selection(bg_id,tea_id,people_id) values (%d,%d,%d)',$bg_id,$tea_id,$people_id);
	if ($mysql->edit($strsql)) {
		$ret["statu"] = "success";
		$ret["error_info"] = "选择成功";
		$select_id =  mysql_insert_id();
		$query = sprintf ("select selection.id as id,people.name as people_name,tea.name as tea_name from selection,people,tea where selection.id = %d and selection.people_id = people.id and tea.id = selection.tea_id",$select_id);
		$result = $mysql->select($query);
		$ret["result"] = $result;
		
	} else {
		$ret["statu"] = "error";
		$ret["error_info"] = "插入失败".$strsql;
	}
} else {
	$strsql = sprintf ('update selection set tea_id = %d where bg_id = %d and people_id = %d',$tea_id,$bg_id,$people_id);
	if ($mysql->edit($strsql)) {
		$ret["statu"] = "success";
		$ret["error_info"] = "更新选择成功";
	} else {
		$ret["statu"] = "error";
		$ret["error_info"] = "更新失败".$strsql;
	}
}




echo json_encode($ret);
?>